
from flask import current_app
from app.models import rangeModel
from tools import db
from tools.basic_tools import Tools
from app.api.v1.webhook.webhook_manager import WebHookManager

def is_within_range(number, lower_bound, upper_bound):
    # 判断是否在范围内
    return lower_bound <= number <= upper_bound


def network_init():
    """初始化网络-生成项目专用vxlan_pool"""
    
    start_vni = 0
    end_vni = 0
    vin_span = current_app.config["ZSTACK_CLOUD"]["vin_span"]

    range_pool = rangeModel.RangeVni.query.all()
    if range_pool:
        return 
    # 获取现在存在最大的vni范围

    load_cloud_object = WebHookManager()
    result = load_cloud_object.get_l2_vxlan_network_pool()
    # 获取范围vni
    range_vni_list = [(res["startVni"], res["endVni"]) for res in result]
    flag = True
    while flag:
        end_vni += vin_span
        start_vni = end_vni - vin_span + 1
        if start_vni > 10000 or   end_vni > 10000:
            print("未找到合适范围的vni范围, 请联系管理员")
            break
        # # 对比下阈值 和下阈值
        for range_vni in range_vni_list:
            if is_within_range(start_vni, *range_vni) or is_within_range(end_vni, *range_vni):
                flag = True
                break
            else:
                flag = False
    try:
        # 创建资源
        vxlan_pool_id = Tools.get_uuid4_no_line()
        load_cloud_object.create_l2_vxlan_network_pool(vxlan_pool_id, 
                                                       vxlan_pool_id, 
                                                       start_vni,
                                                       end_vni,
                                                       user_only=Tools.get_uuid4_no_line())
        # 入库
        range_vni_obj = rangeModel.RangeVni(
            start_vni=start_vni,
            end_vni=end_vni,
            pool_uuid=vxlan_pool_id
        )
        db.session.add(range_vni_obj)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        raise ValueError("启动失败") from e




if __name__ == "__main__":
    network_init()

